<template>
	<gk-city :headtitle="title" :provincedata="provinceData" propText="name" propValue="name" :data="list" mode="cityPicker" ref="cityPicker"
	 @funcvalue="onCityChange" :pickerSize="3" v-if="listType=='city_picker'"></gk-city>
	 <uni-popup ref="popup" v-else-if="popup && popup!='false'" @change="onPopupChange" :type="popup" :isMaskClick="isMaskClick">
	 	<view class='box' style="width:100%;margin-left:0;" :style="(popup=='bottom'?'border-bottom-left-radius: 0;border-bottom-right-radius: 0;':'')+(bottom?'margin-bottom:'+bottom+';':'')+boxStyle" :class="boxClass">
	 		<view class='boxHead'>
	 			<text class="caption" v-if="title">{{title}}</text>
	 			<view class="windowBtn">
	 				<uni-icons type="closeempty" size="20" color='#ccc' @click="onCancel()"></uni-icons>
	 			</view>
	 		</view>
			<view v-if="listType=='tree'" style="width:100%;">
				<scroll-view id="nav-bar" class="nav-bar" scroll-x="true" scroll-with-animation="true" :scroll-left="0" >
					<view v-for="(item,index) in tabList" class="nav-item" :key="index" :id="'tab'+index" @click="changeTab(index)" :class="{'current': index === currentTab}">
						<text class="nav-bar-title">{{item.text}}</text>
					</view>
				</scroll-view>
				<scroll-view scroll-y="true" style="max-height: 70vh;min-height: 300rpx;">
					<view class='textBlock'>
						<view class="blockBody">
							<p-button-group v-model="tabList[currentTab].text" :list="tabList[currentTab].children"  :type="tabList[currentTab].type || type ||'radio'" :returnType="tabList[currentTab].returnType || returnType ||'name'" :propName="tabList[currentTab].propName||'name'" :propId="tabList[currentTab].propId||'id'" :column="tabList[currentTab].column||column||0" buttonStyle="gray" @change="onCheckChange"></p-button-group>
						</view>
					</view>
					<slot></slot>
				</scroll-view>
			</view>
			<scroll-view scroll-y="true" style="max-height: 80vh;min-height: 300rpx;" v-else-if="items && items.length>0">
				<view class='textBlock' v-for="(item,index) in items" :key="index">
					<view class="blockTitle">{{item.title}}</view>
					<view class="blockBody">
						<p-button-group v-model="items[index].value" :list="item.data" :type="item.type || type ||'radio'" :returnType="item.returnType || returnType ||'name'" :propName="item.propName ||'name'" :propId="item.propId||'id'" :column="item.column||column||0" buttonStyle="gray" @change="onCheckChange"></p-button-group>
					</view>
				</view>
				<slot></slot>
			</scroll-view>
			<scroll-view scroll-y="true" style="max-height: 80vh;min-height: 300rpx;" v-else>
				<slot></slot>
			</scroll-view>
	 		<view class="boxFooter margin-top-20" v-if="cancelEnable || okEnable">
	 			<button v-if="cancelEnable" style='color:white;background:#FF9700' @click="onCancel()">{{cancelTitle}}</button>
	 			<button v-if="okEnable" :disabled="okDisable" style='color:white;background:#00a4ff' @click="onConfirm()">{{okTitle}}</button>
	 		</view>	
	 	</view>
	 
	 </uni-popup>
	 <view v-else class='box' :style="boxStyle" :class="boxClass">
	 	<view v-if="listType=='tree'" style="width:100%;">
	 		<scroll-view id="nav-bar" class="nav-bar" scroll-x="true" scroll-with-animation="true" :scroll-left="0" >
	 			<view v-for="(item,index) in tabList" class="nav-item" :key="index" :id="'tab'+index" @click="changeTab(index)" :class="{'current': index === currentTab}">
	 				<text class="nav-bar-title">{{item.text}}</text>
	 			</view>
	 		</scroll-view>
	 		<scroll-view scroll-y="true">
	 			<view class='textBlock'>
	 				<view class="blockBody">
	 					<p-button-group v-model="tabList[currentTab].text" :list="tabList[currentTab].children"  :type="tabList[currentTab].type || type ||'radio'" :returnType="tabList[currentTab].returnType || returnType ||'name'" :propName="tabList[currentTab].propName||'name'" :propId="tabList[currentTab].propId||'id'" :column="tabList[currentTab].column||column||0" buttonStyle="gray" @change="onCheckChange"></p-button-group>
	 				</view>
	 			</view>
	 			<slot></slot>
	 		</scroll-view>
	 	</view>
	 	<scroll-view scroll-y="true" v-else-if="items && items.length>0">
	 		<view class='textBlock' v-for="(item,index) in items" :key="index">
	 			<view class="blockTitle">{{item.title}}</view>
	 			<view class="blockBody">
	 				<p-button-group v-model="items[index].value" :list="item.data" :type="item.type || type ||'radio'" :returnType="item.returnType || returnType ||'name'" :propName="item.propName ||'name'" :propId="item.propId||'id'" :column="item.column||column||0" buttonStyle="gray" @change="onCheckChange"></p-button-group>
	 			</view>
	 		</view>
	 		<slot></slot>
	 	</scroll-view>
	 	<scroll-view scroll-y="true" v-else>
	 		<slot></slot>
	 	</scroll-view>
	 </view>
</template>

<script>
	
	export default {
		props: {
			value: {
				type: [String, Number,Array,Object],
				default: ''
			}, 
			/* 按钮列表 */
			list: {
				type: [Array,Object,String],
				default () {
					return []
				}
			},
			listType: {
				type: [String],
				default () {
					return 'list'
				}
			},
			type: {
				type: [String],
				default () {
					return 'radio'
				}
			},
			popup: {
				type: [String],
				default () {
					return 'bottom'
				}
			},
			/* 标题 */
			title: {
				type: String,
				default () {
					return "请选择"
				}
			},
			/* 单选还是多选 */
			type: {//city_picker,tree,radio,check
				type: String,
				default () {
					return "radio"
				}
			},
			checkData: {
				type: [Array,Object],
				default () {
					return []
				}
			},
			checkRule: {
				type: [Array,Object],
				default () {
					return []
				}
			},
			/* 确认按钮 */
			okTitle: {
				type: String,
				default: '确认'
			},
			okDisable: {
				type: Boolean,
				default () {
					return false
				}
			},
			/* 确认按钮 */
			cancelTitle: {
				type: String,
				default: ''
			},
			/* 单选还是多选 */
			isMaskClick: {
				type: Boolean,
				default () {
					return true
				}
			},
			bottom: {
				type: String,
				default: ''
			},
			boxClass: {
				type: String,
				default: ''
			},
			boxStyle: {
				type: String,
				default: ''
			},
			/* 一行多个个 */
			column: {
				type: [String,Number],
				default () {
					return 0
				}
			},
			
			propId: {
				type: String,
				default: () => {
					return 'id'
				}
			},
			propName: {
				type: String,
				default: () => {
					return 'name'
				}
			},
			returnType: {
				type: String,
				default () {
					return "name"
				}
			},	
			autoClose: {
				type: Boolean,
				default () {
					return true
				}
			},	
		},
		data() {
			return {
				provinceData:[{
					text: '请选择 ',
					value: ''
				}],
				currentTab: 0, //当前选项卡索引
				tabList:[{
					text: '请选择 ',
					data: {},
				}],				
				currentValue: this.value,
				isMaskClose: true, // 是否由点击遮罩层关闭
				items: [],
				initValues:[],
				self:{autoClose:true},
			}
		},
		created() {
			this.self = {
				initTabs:this.initTabs,
				getLastTab:this.getLastTab,
				getTab:this.getTab,
				isTabEnd:this.isTabEnd,
				tabOver:this.tabOver,
				changeTab:this.changeTab,
				newTab:this.newTab,
				tabList:this.tabList,
				open:this.open,
				close:this.close,
				autoClose:true
			};		
			this.self.autoClose = this.autoClose; 
		},
		mounted() {
			//console.log('mounted-------------------------------',this.value);
			this.getList(this.list);
			if (this.bottom && this.popup){
				this.$refs.popup.closeMask();
			}

		},
		computed: {
			okEnable() {
				return this.okTitle && parseInt(this.okTitle.length)>0 && 'true,false'.indexOf(this.okTitle)<0;
			},
			cancelEnable() {
				return this.cancelTitle && parseInt(this.cancelTitle.length)>0 && 'true,false'.indexOf(this.cancelTitle)<0;
			},
		},
		watch:{
			value: {
				handler(newVal) {
					this.currentValue = newVal;
					if (this.currentValue){
						this.initValues = (''+this.currentValue).split('-');
					}else{
						this.initValues =[];
					}
					
				},
				immediate: true
			},
			autoClose: {
				handler(newVal) {
					this.self.autoClose = newVal;
					//console.log('autoClose',this.self.autoClose);
				},
				immediate: true
			},
			list: {
				handler(newVal) {
					
					this.getList(newVal);
				},
				immediate: true
			},
		
			
		},
		methods: {
			
			getList(list){
				this.items = [];
				if (typeof(list)=='string'){
					if (list.indexOf(";\r\n")>=0){
						list = list.split(";\r\n");
					}else if (list.indexOf("\r\n")>=0){
						list = list.split("\r\n");
					}else{
						list = list.split(';');
					}
					
				}
				if (this.listType==='single'){
					let item = {data:list};
					item.propId=this.propId;
					item.propName=this.propName;
					item.column=this.column;
					item.value = this.value;
					this.items.push(item);
				}else if (this.listType==='tree'){
					let children =[];
					for (let i in list) {
						if (list[i]){
							let item ={value:list[i]};
							if (typeof(list[i])==='object') {
								item.id=list[i][this.propId];
								item.name=list[i][this.propName];
							}else{
								item.id=i;
								item.name = list[i];
							 }
							children.push(item);
						}
					}
					this.currentTab = 0;
					let data = {text:'请选择',children:children,value:{}};
					this.tabList[this.currentTab] = data;
					this.$forceUpdate();
				}else{
					let data =[];
					for (let i in list) {
						if (list[i]){
							if (typeof(list[i])==='object') {
								let item =list[i];
								this.items.push(item);
							}else{
								data.push({id:i,name:list[i]})
							}
							
						}
					}
					//console.log('data',JSON.stringify(data));
					if (data && data.length>0){
						let item={data:data,value:this.currentValue};
						item.propId=this.propId||'id';
						item.propName=this.propName||'name';
						item.column=this.column||0;						
						this.items.push(item);
					}
					
				}
				// console.log('list',JSON.stringify(list));
				// console.log('items',JSON.stringify(this.items));
			},
			initTabs(event=false,values=''){
				if (values){
					this.initValues = values.split('-');
				}
				if (this.listType=='single'){
					let value='',item={},ret = false
					let children = this.list;
					let propId = this.propId || 'id';
					let propName = this.propName || 'name';
					let returnType = this.returnType;
					let index = 0;
					for(let i in children){
						item = children[i];
						if (returnType=='id'){
							value = item[propId];
						}else if (returnType=='name'){
							value = item[propName];
						}else{
							value = item;
						}
						if (this.initValues[this.currentTab]==value){
							index = i;
							item  = children[i];
							ret = true;
							break;
						}
					}
					if (ret){
						let data = {text:value,over:true,children:children,value:item};
						this.onCheckChange(index,value,data,event);
					}
				}else if (this.initValues.length>=this.tabList.length){
					
					if (!this.tabList[this.currentTab].value || (JSON.stringify(this.tabList[this.currentTab].value) == "{}")){
						let value='',item={},ret = false,tab=this.tabList[this.currentTab];
						let children = tab.children;
						let propId = tab.propId || 'id';
						let propName = tab.propName || 'name';
						let returnType = tab.returnType || this.returnType;
						let index = 0;
						for(let i in children){
							item = children[i];
							if (returnType=='id'){
								value = item[propId];
							}else if (returnType=='name'){
								value = item[propName];
							}else{
								value = item;
							}
							if (this.initValues[this.currentTab]==value){
								index = i;
								item  = children[i];
								ret = true;
								break;
							}
						}
						
						if (ret){
							
							this.onCheckChange(index,value,item,event);
						}
					}
				}
			},
			open() {
				if (this.listType==='city_picker'){
					this.$refs["cityPicker"].show();
				}else{
					this.initTabs();
					if (this.popup&&  this.$refs.popup && this.$refs.popup.open) this.$refs.popup.open();
				}
			},
			close() {
				//console.log('close');
				if (this.listType==='city_picker'){
					this.$refs["cityPicker"].hide();
				}else{
					this.isMaskClose = false;
					if (this.popup &&  this.$refs.popup && this.$refs.popup.close) this.$refs.popup.close();
				}				

			},
			onCancel() {
				this.$emit('cancel', this.currentValue);
				this.close();
			},
			haveChek(){
				if (this.checkData){
					for (let i in this.checkRule ){
						return true;
					}
					return false;
				}else{
					return false;
				}
			},
			onCheck(value){
				if (this.haveChek()){
					let ret = this.validator.check(this.checkRule,this.checkData);
					return ret===false;
				}else{
					let ret = {result:true,msg:''};
					this.$emit('check', ret,value);
					if (!ret.result && ret.msg){
						this.dialog.toast(ret.msg);
					}
					//console.log('ret.result',ret.result);
					return ret.result;
				}

			},
			onConfirm() {
				//console.log('onConfirm');
				if (this.listType=='tree'){
					let value = '';
					let tabs = [];
					for(let i in this.tabList){
						if (this.tabList[i].value){
							tabs.push(this.tabList[i].value);
							value += this.tabList[i].text+'-';
						}
					} 
					if (value!=='') value = value.substr(0,value.length-1);
					if (this.onCheck(this.currentValue)){
						this.$emit('confirm', this.self,tabs);
						this.$emit('input', value);
						this.$emit("change", tabs);	
						if (this.self.autoClose){
							this.close();
						}
						
					}									
				
				}else if(this.listType=='single') {
					this.$emit('input', this.currentValue);
					this.$emit('confirm', this.self,this.currentItem);
					this.$emit("change", this.currentValue);							
					if (this.self.autoClose){
						this.close();
					}
				
				}else {
					if (this.list.length==this.items.length){
						for (let i in this.list) {
							this.list[i].value = this.items[i].value ;
						}					
					}
					if (this.onCheck(this.currentValue)){
						this.$emit('input', this.currentValue);
						this.$emit('confirm', this.self,this.list);
						this.$emit("change", this.list);							
						if (this.self.autoClose){
							console.log('this.self.autoClose',this.self.autoClose);
							this.close();
						}
					}
					//console.log('test11111111111');
				
				}

				
				
			},
			onOver() {
				//console.log('onConfirm');
				if (this.listType=='tree'){
					let value = '';
					let tabs = [];
					for(let i in this.tabList){
						if (this.tabList[i].value){
							tabs.push(this.tabList[i].value);
							value += this.tabList[i].text+'-';
						}
					} 
					if (value!=='') value = value.substr(0,value.length-1);
					this.$emit('over', this.self,value);
				
				}else {
					if (this.list.length==this.items.length){
						for (let i in this.list) {
							this.list[i].value = this.items[i].value ;
						}					
					}
					this.$emit('over', this.self,this.currentValue);
					//console.log('test11111111111');
				}
			},
			getTab(tabIndex){
				return this.tabList[tabIndex];
			},
			getLastTab(){
				return this.tabList[this.tabList.length-1];
			},
			newTab(list,propId,propName,over=false,text='请选择',event=false){
				//console.log('newTab');
				let currentTab = this.currentTab +1;
				let children =[];
				for (let i in list) {
					if (list[i]){
						let item ={value:list[i]};
						if (typeof(list[i])==='object') {
							item.id=list[i][propId||this.propId];
							item.name=list[i][propName||this.propName];
						}else{
							item.id=i;
							item.name = list[i];
						 }
						children.push(item);
					}
				}	
				let data = {text:text,over:over,children:children,value:{}};//propId:propId,propName:propName,
				this.tabList[currentTab] = data;
				this.currentTab = currentTab;
				this.tabList = this.tabList.slice(0,currentTab+1);
				this.initTabs(event);
			},
			tabOver(){
				console.log('tabOver');
				if (!this.okEnable){
					this.onConfirm();
				}
				this.onOver();
			},
			isTabEnd(){
				let ret = false;
				//console.log('this.currentTab',this.currentTab);
				//console.log('this.tabList[this.currentTab]',this.tabList[this.currentTab]);
				if (this.tabList.length>this.currentTab && this.currentTab>=0){
					ret = this.tabList[this.currentTab].over?true:false;
				}
				return ret;
			},
			onCheckChange(index,value,item,event=false){
				let over = false;
				//console.log('event==============================',JSON.stringify(event));
				if (this.listType=='tree'){
					if (this.tabList[this.currentTab] && this.tabList[this.currentTab].children){
						this.tabList[this.currentTab].text = value;
						over = this.isTabEnd();
						 
						if (item){
							let tab =this.tabList[this.currentTab];
							this.tabList[this.currentTab].value = item.value;
							if ('children' in item && item.children.length>0){
								this.newTab(item.children,tab.propId || item.propId,tab.propName || item.propName,false,'请选择',event);
							}else{
								//console.log('children.start');
								this.$emit("children", this.self,this.currentTab,item.value,event);
								//console.log('children.end');
							}
						}
						//this.$forceUpdate();

					}
					//console.log(JSON.stringify(item));
					this.currentValue = value;
					this.currentItem = item;
					if (!this.okEnable && event && over ){
						this.onConfirm();
					}
		
				}else{
					//console.log('event',JSON.stringify(event));
					this.currentValue = value;
					this.currentItem = item;
					if (!this.okEnable && event){
						this.onConfirm();
					}
				}
				
				
				
			},
			onPopupChange(e) {
				// 捕捉uniPopup点击遮罩层关闭事件
				if (!e.show) {
					if (this.isMaskClose) {
						this.$emit('cancel', this.currentValue);
					}
					this.isMaskClose = true
				}
				this.$emit("popup_change", e);
			},
			onCityChange(data) {
				this.provinceData = data;
				this.currentValue = data[0].text + data[1].text + data[2].text;
				this.$emit('confirm', this.currentValue);
				this.$emit('input', this.currentValue);
				this.$emit("change", this.currentValue);
			},
			//tab切换
			changeTab(e){
				this.currentTab = e;
				if (this.popup){
					this.tabList.splice(e+1,this.tabList.length-e-1);
				}
				
				//console.log('changeTab',e);
			},
		
		}
	}
</script>

<style scoped>
	.nav-bar {
	    position: relative;
		margin-top:10upx;
	    z-index: 10;
	    height: 42px;
	    white-space: nowrap;
	    background-color: #fff;
		border-bottom: 1px solid #f8f8f8;
	}
	/* #ifndef APP-NVUE */
	.nav-bar::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}
	/* #endif */
	.nav-item {
	    /* #ifndef APP-NVUE */
	    display: inline-flex!important;
	    /* #endif */
	    /* #ifdef APP-NVUE */
	    flex-direction: row!important;
	    /* #endif */
	    width: 170rpx;
	    padding: 7px 0px;
	    line-height: 26px;
	    align-items: center;
	    justify-content: center;
	    color: #303133;
	    position: relative;
	    overflow: hidden;
	    text-overflow: ellipsis;
	}
	.nav-bar-title {
	    font-size: 14px;
	}
	.current {
	    color: #00a4ff;
	    border-color: #00a4ff;
	    border-bottom-width: 4rpx;
	    border-bottom-style: solid;
	}
	.current:after {
	    width: 50%;
	}
</style>
